﻿using System;
using System.Web;
using Rob.SampleCode.MyApp.Core;
using Rob.SampleCode.MyApp.Infrastructure;
using StructureMap;
using StructureMap.ServiceLocatorAdapter;

namespace Rob.SampleCode.MyApp.Webforms
{
    public class Global : HttpApplication
    {
        protected void Application_Start(object sender, EventArgs e)
        {
            InitializeIoc();
        }

        protected void Application_EndRequest(object sender, EventArgs e)
        {
            Ioc.Resolve<NHibernateUnitOfWork>().End();
        }

        protected void Application_Error(object sender, EventArgs e)
        {
            if (HttpContext.Current == null || HttpContext.Current.Session == null)
                return;

            var unhandledException = Server.GetLastError();
            Server.ClearError();

            if (unhandledException == null)
                return;

            if (unhandledException is HttpUnhandledException && unhandledException.InnerException != null)
                unhandledException = unhandledException.InnerException;

            HttpContext.Current.Session["UnhandledException"] = unhandledException;
            Response.Redirect("~/Error.aspx");
        }

        private static void InitializeIoc()
        {
            ObjectFactory.Initialize(x =>
            {
                x.For<NHibernateUnitOfWork>().HybridHttpOrThreadLocalScoped().Use<NHibernateUnitOfWork>();
                x.For<IRepository>().Use<NHibernateRepository>();
                x.Scan(scanner =>
                {
                    scanner.Assembly("Rob.SampleCode.MyApp.Core");
                    scanner.Assembly("Rob.SampleCode.MyApp.Infrastructure");
                    scanner.WithDefaultConventions();
                });
            });

            Ioc.Initialize(new StructureMapServiceLocator(ObjectFactory.Container));
        }
    }
}